import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
// import { getToken } from '@/utils/auth' // Session认证下不再需要

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 60000,
  withCredentials: true // 【关键】开启Cookie携带
})

// request拦截器
service.interceptors.request.use(
  config => {
    // Session认证，无需手动设置Token
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== "000000") {
      Message({
        message: res.mesg,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject('业务错误')
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error)
    if (error.response && error.response.status === 401) {
      MessageBox.confirm(
        '你已被登出，请重新登录',
        '确定登出',
        {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        store.dispatch('FedLogOut').then(() => {
          location.reload()
        })
      })
    } else {
      Message({
        message: error.message || "出现异常",
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
